package com.celesea.framework.util;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringKit {

    /**
     * @param seq
     * @return
     */
    public static boolean isEmpty(CharSequence seq) {
        return seq == null || seq.length() == 0;
    }

    /**
     * @param seq
     * @return
     */
    public static boolean isBlank(CharSequence seq) {
        return isEmpty(seq);
    }

    /**
     * @param seq
     * @return
     */
    public static boolean isNotEmpty(CharSequence seq) {
        return !isEmpty(seq);
    }

    /**
     * @param strings
     * @return
     */
    public static boolean isAnyNotEmpty(String... strings) {
        if (CollectionKit.isEmptyArray(strings)) {
            return true;
        }
        for (String string : strings) {
            if (isNotEmpty(string)) {
                return true;
            }
        }
        return false;
    }

    /**
     * @param strings
     * @return
     */
    public static boolean isAnyEmpty(String... strings) {
        if (CollectionKit.isEmptyArray(strings)) {
            return true;
        }
        for (String string : strings) {
            if (isEmpty(string)) {
                return true;
            }
        }
        return false;
    }

    /**
     * @param key
     * @param strings
     * @return
     */
    public static boolean isEqualToAny(String key, String... strings) {
        if (isEmpty(key)) {
            return false;
        }
        if (CollectionKit.isEmptyArray(strings)) {
            return false;
        }
        for (String string : strings) {
            if (key.equals(string)) {
                return true;
            }
        }
        return false;
    }

    /**
     * @param objs
     * @return
     */
    public static boolean isNotNull(Object... objs) {
        return !isNull(objs);
    }

    /**
     * @param objs
     * @return
     */
    public static boolean isNull(Object... objs) {
        if (CollectionKit.isEmptyArray(objs)) {
            return true;
        }
        for (Object obj : objs) {
            if (obj == null || isEmpty(obj.toString())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 替换掉HTML标签方法
     */
    public static String replaceHtml(String html) {
        if (isBlank(html)) {
            return "";
        }
        String regEx = "<.+?>";
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(html);
        return matcher.replaceAll("");
    }

    /**
     * 缩略字符串（不区分中英文字符）
     *
     * @param str    目标字符串
     * @param length 截取长度
     * @return
     */
    public static String abbr(String str, int length) {
        if (str == null) {
            return "";
        }
        try {
            StringBuilder builder = new StringBuilder();
            int currentLength = 0;
            for (char c : str.toCharArray()) {
                currentLength += String.valueOf(c).getBytes("GBK").length;
                if (currentLength <= length - 3) {
                    builder.append(c);
                } else {
                    builder.append("...");
                    break;
                }
            }
            return builder.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * @param value
     * @param clazz
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T asType(Object value, Class<T> clazz) {
        T t = null;
        if (clazz.equals(Integer.class) || clazz.equals(int.class)) {
            t = (T) toInteger(value);
        } else if (clazz.equals(Long.class) || clazz.equals(long.class)) {
            t = (T) toLong(value);
        } else if (clazz.equals(Float.class) || clazz.equals(float.class)) {
            t = (T) toFloat(value);
        } else if (clazz.equals(Double.class) || clazz.equals(double.class)) {
            t = (T) toDouble(value);
        } else {
            t = (T) value;
        }
        return t;
    }

    /**
     * 转换为Double类型
     */
    public static Double toDouble(Object val) {
        if (val == null) {
            return 0D;
        }
        try {
            return Double.valueOf(val.toString().trim());
        } catch (Exception e) {
            return 0D;
        }
    }

    /**
     * 转换为Float类型
     */
    public static Float toFloat(Object val) {
        return toDouble(val).floatValue();
    }

    /**
     * 转换为Long类型
     */
    public static Long toLong(Object val) {
        return toDouble(val).longValue();
    }

    /**
     * 转换为Integer类型
     */
    public static Integer toInteger(Object val) {
        return toLong(val).intValue();
    }

    /**
     * @param chars
     * @return
     */
    public static String charsToString(char[] chars) {
        StringBuffer buffer = new StringBuffer();
        if (chars == null || chars.length == 0) {
            return buffer.toString();
        }
        buffer.append(chars);
        return buffer.toString();
    }

    /**
     * @param src
     * @param tar
     * @return
     */
    public static boolean isNotEqual(String src, String tar) {
        return !isEqual(src, tar);
    }

    /**
     * @param src
     * @param tar
     * @return
     */
    public static boolean isEqual(String src, String tar) {
        if (isEmpty(src) || isEmpty(tar)) {
            return false;
        }
        return src.equals(tar);
    }

    /**
     * @param src
     * @param tar
     * @return
     */
    public static boolean isNullOrEqual(String src, String tar) {
        if (isEmpty(src) && isEmpty(tar)) {
            return true;
        }
        if (isEmpty(src)) {
            return false;
        }
        return src.equals(tar);
    }

    /**
     * @param str
     * @return
     */
    public static int stringToInteger(String str) {
        StringBuffer buffer = new StringBuffer();
        while (StringKit.isNotEmpty(str)) {
            char first = str.charAt(0);
            if (Character.isDigit(first)) {
                buffer.append(first);
            } else {
                buffer = new StringBuffer();
            }
            str = str.substring(1);
        }
        return Integer.parseInt(buffer.toString());
    }

    /**
     * @param count
     * @param length
     * @return
     */
    public static String appendPrefixZero(int count, int length) {
        String after = String.valueOf(count);
        while (length > after.length()) {
            after = "0" + after;
        }
        return after;
    }

    /**
     * @param dataType
     * @return
     */
    public static boolean isBasicDataType(String dataType) {
        if (isItemDataType(dataType) || isMappingDataType(dataType) || isEqualToAny(dataType, "java.com.celesea.framework.util.List", "java.com.celesea.framework.util.Map")) {
            return false;
        }
        return true;
    }

    /**
     * @param dataType
     * @return
     */
    public static boolean isItemDataType(String dataType) {

        return "object.item".equals(dataType);
    }

    /**
     * @param dataType
     * @return
     */
    public static boolean isMappingDataType(String dataType) {

        return "object.mapping".equals(dataType);
    }

    /**
     * 是否为class类型
     *
     * @param clazz
     * @param className
     * @return
     */
    public static boolean isClassType(Class<?> clazz, String className) {
        if (clazz == null) {
            return false;
        }
        return clazz.getName().equals(className);
    }

    /**
     * 验证电话号码
     *
     * @param phone
     * @return
     */
    public static boolean isPhone(String phone) {
        boolean flag = false;
        String expression = "((^(13|15|17|18)[0-9]{9}$)|(^0[1,2]{1}\\d{1}-?\\d{8}$)|(^0[3-9] {1}\\d{2}-?\\d{7,8}$)|(^0[1,2]{1}\\d{1}-?\\d{8}-(\\d{1,4})$)|(^0[3-9]{1}\\d{2}-? \\d{7,8}-(\\d{1,4})$))";
        Pattern pattern = Pattern.compile(expression);
        Matcher matcher = pattern.matcher(phone);
        if (matcher.matches()) {
            flag = true;
        }
        return flag;
    }

    /**
     * 获取发送数据
     *
     * @param content
     * @param map
     * @return String
     */
    public static String getSendContent(String content, Map<String, String> map) {
        List<String> list = convertList(content);
        if (CollectionKit.isNotEmpty(list)) {
            // 检测参数是否匹配
            if (!checkParam(list, map)) {
                throw new IllegalArgumentException("传入的参数与模板中的参数不匹配");
            }
            // 替换{}里的值
            content = replaceContent(content, list, map);
            content = content.replace("${", "").replace("}", "");
        }
        return content;
    }

    /**
     * 截取去内容中{}的值，转换成List
     *
     * @param content
     * @return List<String>
     */
    private static List<String> convertList(String content) {
        List<String> list = new ArrayList<String>();
        if (content.contains("${") && content.contains("}")) {
            String[] st = content.split("}");
            if (content.endsWith("}")) {
                for (int i = 0; i < st.length; i++) {
                    list.add(st[i].substring(st[i].indexOf("{") + 1));
                }
            } else {
                for (int i = 0; i < st.length - 1; i++) {
                    list.add(st[i].substring(st[i].indexOf("{") + 1));
                }
            }
        }
        return list;
    }

    /**
     * 检测参数是否匹配
     *
     * @param list
     * @param map
     * @return boolean.true：匹配；false：不匹配
     */
    private static boolean checkParam(List<String> list, Map<String, String> map) {
        for (String str : list) {
            if (map.get(str) == null) {
                return false;
            }
        }
        return true;
    }

    /**
     * 替换{}里的值
     *
     * @param content
     * @param list
     * @param map
     * @return String
     */
    private static String replaceContent(String content, List<String> list, Map<String, String> map) {
        for (String str : list) {
            content = content.replace(str, map.get(str));
        }
        return content;
    }

    /**
     * 构建sql 忽略关键字
     *
     * @param column
     * @return
     */
    public static String ingoreKeyword(String column) {
        return " `" + column + "` ";
    }

    public static String defaultIfBlank(String a, String b) {
        return isEmpty(a) ? b : a;
    }
}
